package controller

import (
	"net/http"
	"net/http/httputil"
	"net/url"
	"strconv"
	"time"
	"webssh/src/core"
	"webssh/src/logger"
	"webssh/src/response"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// CheckSSH 检查ssh连接是否能连接
func CheckSSH(c *gin.Context) *response.ResponseBody {
	tenantId := c.GetString("tenantId")
	username := c.GetString("username")

	sshClient, err := core.NewSSHClient(tenantId, username)
	if err != nil {
		logger.Info(err.Error())
		return response.ErrCreateSSHClient
	}

	err = sshClient.GenerateClient()
	defer sshClient.Close()

	if err != nil {
		logger.Info(err.Error())
		return response.ErrCreateSSHClient
	}
	return response.SuccessResponse
}

// path=api/gcp-hpc01/login-01/webvnc/5930
// /webvnc/5930
func ProxyVnc(c *gin.Context, timeout time.Duration) *response.ResponseBody {
	// path := c.Request.URL.Path

	// pas := strings.Split(path, "/")
	// if len(pas) != 2 {
	// 	logger.Info("request path error, %s", path)
	// 	return response.ErrCreateWebsocket
	// }
	port := c.Param("port")
	target := "ws://localhost:" + port

	targetUrl, err := url.Parse(target)
	if err != nil {
		logger.Info("parse uri %s err, %v", targetUrl, err)
		return response.ErrCreateWebsocket
	}
	logger.Info("wsUrl: %s", targetUrl)
	proxy := httputil.NewSingleHostReverseProxy(targetUrl)

	proxy.Director = func(req *http.Request) {
		req.Header = c.Request.Header
		req.Host = targetUrl.Host
		req.URL.Scheme = "http"
		req.URL.Host = targetUrl.Host
		req.URL.Path = "websockify"
	}

	proxy.ServeHTTP(c.Writer, c.Request)
	logger.Info("connect websocket success")
	return response.SuccessResponse
}

// TermWs 获取终端ws
func TermWs(c *gin.Context, timeout time.Duration) *response.ResponseBody {
	tenantId := c.GetString("tenantId")
	username := c.GetString("username")
	cols := c.DefaultQuery("cols", "150")
	rows := c.DefaultQuery("rows", "35")
	closeTip := c.DefaultQuery("closeTip", "Connection timed out!")
	col, _ := strconv.Atoi(cols)
	row, _ := strconv.Atoi(rows)

	sshClient, err := core.NewSSHClient(tenantId, username)
	if err != nil {
		logger.Info("generate ssh err", err)
		return response.ErrCreateSSHClient
	}
	wsConn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		logger.Info("upgrader ws err", err)
		return response.ErrCreateWebsocket
	}
	err = sshClient.GenerateClient()
	if err != nil {
		wsConn.WriteMessage(1, []byte(err.Error()))
		wsConn.Close()
		logger.Info("generate client err, %v, sshClient, %v", err, sshClient)
		return response.ErrCreateSSHClient
	}
	sshClient.InitTerminal(wsConn, row, col)
	sshClient.Connect(wsConn, timeout, closeTip)
	logger.Info("connect websocket success")
	return response.SuccessResponse
}
